package com.ruoyi.common.utils.poi;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;

import java.util.List;
import java.util.Map;

/**
 * word相关处理
 *
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class XWPFDocumentUtil {

    /**
     * 替换内容
     * @param document
     * @param placeholder
     * @param replacement
     * @return
     */
    public static XWPFDocument replaceText(XWPFDocument document, String placeholder, String replacement) {
        for (XWPFParagraph p : document.getParagraphs()) {
            List<XWPFRun> runs = p.getRuns();
            if (runs != null) {
                for (XWPFRun r : runs) {
                    String text = r.getText(0);
                    if (text != null && text.contains(placeholder)) {
                        text = text.replace(placeholder, replacement);
                        r.setText(text, 0);
                    }
                }
            }
        }
        return document;
    }

    /**
     * 遍历map替换内容
     * @param document
     * @return
     */
    public static XWPFDocument replaceTextMap(XWPFDocument document, Map<String, String> map) {
        for (Map.Entry<String, String> entry : map.entrySet()) {
            for (XWPFParagraph p : document.getParagraphs()) {
                List<XWPFRun> runs = p.getRuns();
                if (runs != null) {
                    for (XWPFRun r : runs) {
                        String text = r.getText(0);
                        if (text != null && text.contains(entry.getKey())) {
                            text = text.replace(entry.getKey(), entry.getValue());
                            r.setText(text, 0);
                        }
                    }
                }
            }

        }
        return document;
    }

}
